package com.zrx.app.android.activity;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zrx.app.android.R;
import com.zrx.app.android.UTIL.NetworkStatus;
import com.zrx.app.android.UTIL.RemoteConn;
import com.zrx.app.android.UTIL.ZRXUTIL;
import com.zrx.app.android.ZRXApplication;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * A login screen that offers login via email/password.
 *
 *
 * 登录页面
 */
public class LoginActivity extends AppCompatActivity {

    private static final String TAG = "ZRX_LOGIN_ACTIVITY";
    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;
    private EditText mPasswordView;
    private ToggleButton swBtn;
    private View mProgressView;
    private View mLoginFormView;
    private Button btnNewVersion;

    private SharedPreferences sp;
    private Button stagMoneyBT;
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

       getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        stagMoneyBT= (Button) findViewById(R.id.stag_money_bt);
        stagMoneyBT.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(LoginActivity.this,StagMoneyActivity.class);
                startActivity(intent);
            }
        });
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        mPasswordView = (EditText) findViewById(R.id.password);
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
        swBtn = (ToggleButton) findViewById(R.id.sw_test_prod_btn);//测试按钮
        btnNewVersion = (Button) findViewById(R.id.BTN_NEWVERSION);//更新按钮

        Button btnCalTool = (Button) findViewById(R.id.btnCalTool);//计算工具按钮
        btnCalTool.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                CalculatorActivity.startActivity(LoginActivity.this);
            }
        });


        sp = this.getSharedPreferences(getString(R.string.shared_preferences_file_name), Context.MODE_PRIVATE);

        mEmailView.setText(sp.getString("email",""));







        // Set up the login form.
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                attemptLogin();
                return false;
            }
        });

        Button mEmailSignInButton = (Button) findViewById(R.id.sign_in_button);//登录按钮
        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }

        });


        boolean isTest = ZRXApplication.getAppContext().getResources().getBoolean(R.bool.isTest);
        swBtn.setEnabled(isTest);
        swBtn.setChecked(!isTest);
        swBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked)
                {
                    Log.d(TAG,"checked");
                }
                else
                {
                    mEmailView.setText("test1@hotmail.com");
                    mPasswordView.setText("test1");
                    Log.d(TAG,"not checked");
                }
            }
        });


        btnNewVersion.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View v) {
                AsyncTask at=new AsyncTask() {
                    @Override
                    protected Object doInBackground(Object[] params) {
                        try {
                            URL url = new URL("https://ezcleasing.com/appVersion.json");
                            URLConnection urlConnection = url.openConnection();
                            InputStream in = urlConnection.getInputStream();
                            JSONObject re= JSON.parseObject(RemoteConn.getResult(in));
                            return re.getString("version");
                        }catch (Exception e){

                        }
                        return "0";
                    }

                    @Override
                    protected void onPostExecute(Object o) {
                        super.onPostExecute(o);
                        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(v.getContext());
                        builder.setTitle("应用更新检查");
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

                        try{
                            String appVersionStr=getResources().getString(R.string.version);
                            double appVersion=Double.valueOf(appVersionStr);
                            String remoteVersionStr= (String) o;
                            double remoteVersion=Double.valueOf(remoteVersionStr);
                            builder.setMessage("本地版本:"+appVersionStr+"\n服务器版本:"+remoteVersionStr);
                            if(remoteVersion>appVersion){
                                builder.setPositiveButton("点击更新", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent intent = new Intent();
                                        intent.setAction("android.intent.action.VIEW");
                                        Uri content_url = Uri.parse("https://ezcleasing.com/zrx.apk");
                                        intent.setData(content_url);
                                        startActivity(intent);
                                        dialog.dismiss();
                                    }
                                });

                                builder.show();
                                return;
                            }

                        }catch (Exception e){
                            builder.setMessage("没有更新");
                        }

                        builder.show();
                        return;

                    }
                };
                at.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            }
        });



        if(ContextCompat.checkSelfPermission(ZRXApplication.getAppContext(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ZRXUTIL.requestLocationPermission(this);
            AlertDialog ad = new AlertDialog.Builder(this).setMessage("请允许权限，如果已经设置成禁止请到设置中选择允许").setNegativeButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    String lastLoginDate = sp.getString("lastLoginDate", "");
                    if(sdf.format(new Date()).equals(lastLoginDate)){
                        mPasswordView.setText(sp.getString("password",""));
                        attemptLogin();
                    }
                }
            }).show();
        }else {
            String lastLoginDate = sp.getString("lastLoginDate", "");
            if(sdf.format(new Date()).equals(lastLoginDate)){
                mPasswordView.setText(sp.getString("password",""));
                attemptLogin();
            }
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {

        try {


            sp = getSharedPreferences(getString(R.string.shared_preferences_file_name), Context.MODE_PRIVATE);
            String email = mEmailView.getText().toString();
            if (!email.equals("")){
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("email", email);
                editor.commit();
            }

        }catch (Exception e){

        }

        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);

            mAuthTask = new UserLoginTask(email, password);
            mAuthTask.execute();
//            mAuthTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    }

    private boolean isEmailValid(String email) {
        //TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 4;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case ZRXUTIL.MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;
        private final String mPassword;
        private Handler uiHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                // Activity跳转
//                Intent intent = new Intent(LoginActivity.this, SelectActivity.class);
//                startActivity(intent);

                ContentActivity.startActivity(LoginActivity.this);
//                Intent intent = new Intent(LoginActivity.this, ListActivity.class);
//                startActivity(intent);
            }
        };

        UserLoginTask(String email, String password) {
            mEmail = email;
            mPassword = password;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                RemoteConn.createInstance(mEmail,mPassword);
                JSONObject result = RemoteConn.getInstance().login();
                Log.d(TAG, result.toJSONString());
                return result != null && result.getIntValue("code") == 0;

            } catch (Exception e) {
                Log.e(TAG, "err: " + e.toString());
            }
            return false;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {

                Toast.makeText(getApplicationContext(),"login succeed",Toast.LENGTH_SHORT).show();

                sp = getSharedPreferences(getString(R.string.shared_preferences_file_name), Context.MODE_PRIVATE);
                String email = mEmailView.getText().toString();
                String password = mPasswordView.getText().toString();
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("email", email);
                editor.putString("password", password);
                editor.putString("lastLoginDate",sdf.format(new  Date()));
                editor.commit();



                //调用uiHandler
                Message msg = new Message();
                uiHandler.sendMessage(msg);
                //finish();
            } else {
                if (NetworkStatus.isNetworkAvailable(getBaseContext()))
                    mPasswordView.setError(getString(R.string.error_incorrect_password));
                else
                    mPasswordView.setError(getString(R.string.error_network_not_available));

                mPasswordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}
